<?php
namespace App\Supports\Auth\Wechat;

use App\Models\User;
use App\Events\NewUserRegisteredEvent;

class WechatLogger extends WechatAuth
{
	protected function authNew()
	{
		$data = $this->authData;
		
		return User::create([
			'grade' => 'normal',
			'name' => $data->getNickname(),
			'avatar' => $data->getAvatar(),
			'wx_openid' => $data->getId(),
			'wx_unionid' => $data->getRaw()['unionid'] ?? null,
			'wx_nickname' => $data->getNickname(),
			'wx_headimgurl' => $data->getRaw()['headimgurl'],
			'wx_sex' => $data->getRaw()['sex'],
			'wx_country' => $data->getRaw()['country'],
			'wx_province' => $data->getRaw()['province'],
			'wx_city' => $data->getRaw()['city'],
		]);
	}
	
	protected function authOld(User $user)
	{
		$updateData = [];
		
		if (empty($user->wx_unionid) and $this->unionid) {
			$updateData['wx_unionid'] = $this->unionid;
		}
		if (empty($user->wm_openid) and $this->openid) {
			$updateData['wm_openid'] = $this->openid;
		}
		
		if (!empty($updateData)) {
			$user->update($updateData);
		}
		return $user;
	}
	
	protected function auth()
	{
		$this->httpValidate();
		
		$user = null;
		
		if ($this->unionid) {
			$user = User::where('wx_unionid', $this->unionid)->first();
		}
		if (!$user and $this->openid) {
			$user = User::where('wx_openid', $this->openid)->first();
		}
		
		if (! $user) {
			$user = $this->authNew();
			event(new NewUserRegisteredEvent($user));
			return $user;
		}
		
		return $this->authOld($user);
	}
	
	public function login()
	{
		return $this->auth();
	}
}
